package com.shop.api;

import com.shop.ex.ShoppingException;
import com.shop.po.R;
import com.shop.user.mqHandler.sentMessage.OrderCancelHandler;
import com.shop.user.po.dto.UserDto;
import com.shop.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 用户信息 前端控制器
 * </p>
 *
 * @author banxia
 * @since 2023-02-21
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderCancelHandler orderCancelHandler;

    @GetMapping("/testSendMessage/{message}")
    public R testSendMessage(@PathVariable("message") String message){
        orderCancelHandler.sendToExchange(message);
        return R.ok("ok");
    }


    @PostMapping("/edit")
    public R editUserInfo(@RequestBody(required = false) UserDto userDto,
                          @RequestParam(required = false) String password){
        if (userDto==null && password==null){
            ShoppingException.ThrowShoppingException("操作失败，请参数参数");
        }
        userService.editUserInfo(userDto,password);
        return R.ok("成功编辑用户信息");
    }



    @GetMapping("/getInfo")
    public R getUserInfo(){
        UserDto userDto=userService.getUserInfo();
        return R.ok("成功获取用户信息").data("user",userDto);
    }

    @PostMapping("/register")
    public R register(@RequestBody UserDto userDto,
                      @RequestParam("password") String password,
                      @RequestParam("code") String code) {
        userService.register(userDto,password,code);
        return R.ok();
    }

    @PostMapping("/loginByPassword/{account}/{password}")
    public R loginByPassword(@PathVariable String account, @PathVariable String password) {
        String token=userService.loginByPassword(account, password);
        return R.ok("登录成功").data("token",token);
    }

    @PostMapping("/loginByCode/{phone}/{code}")
    public R loginByCode(@PathVariable String phone, @PathVariable String code) {
        String token=userService.loginByCode(phone, code);
        return R.ok("登录成功").data("token",token);
    }

    /**
     * 发送验证码
     * @param phone
     * @param type:验证码用途
     */
    @GetMapping("/sendMessage/{phone}/{type}")
    public R sendMessage(@PathVariable("phone") String phone,@PathVariable("type") String type){
        return userService.sendMessage(phone,type);
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/uploadFile/{type}")
    public R uploadFile(@RequestParam("file") MultipartFile file,@PathVariable("type") String type){
        return userService.uploadFile(file,type);
    }


}

